package com.hc.homestay.config.intercepors;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hc.homestay.pojo.ToStaff;
import com.sun.istack.Nullable;

@Component
public class LoginInterceptor implements HandlerInterceptor {

	// 这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		//System.out.println("执行了TestInterceptor的preHandle方法");
		try {
			// 统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
			ToStaff user = (ToStaff) request.getSession().getAttribute("toStaff");
			if (user != null) {
				return true;
			}
			response.sendRedirect("/login.html");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;// 如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
						// 如果设置为true时，请求将会继续执行后面的操作
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
	}

}
